package com.yonyoucloud.fi.pcm.track.billrule.unionRealWeight;

import com.yonyou.ucf.mdd.common.model.rule.RuleExecuteResult;
import com.yonyou.ucf.mdd.ext.bill.rule.base.AbstractCommonRule;
import com.yonyou.ucf.mdd.ext.bill.service.BillMasterOrgService;
import com.yonyou.ucf.mdd.ext.core.AppContext;
import com.yonyou.ucf.mdd.ext.dao.meta.MetaDaoHelper;
import com.yonyou.ucf.mdd.ext.exceptions.BusinessException;
import com.yonyou.ucf.mdd.ext.model.BillContext;
import com.yonyou.ucf.mdd.ext.model.LoginUser;
import com.yonyoucloud.fi.pcm.consts.ResponseMessage;
import com.yonyoucloud.fi.pcm.realco.RealCo;
import com.yonyoucloud.fi.pcm.rule.ProductType;
import com.yonyoucloud.fi.pcm.rule.UnionRealWeight;
import com.yonyoucloud.fi.pcm.util.PcmHelper;
import com.yonyoucloud.fi.pcm.util.PcmVoucherUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.imeta.core.base.ConditionOperator;
import org.imeta.core.lang.NumberUtils;
import org.imeta.orm.base.BizObject;
import org.imeta.orm.base.EntityStatus;
import org.imeta.orm.schema.QueryCondition;
import org.imeta.orm.schema.QueryConditionGroup;
import org.imeta.orm.schema.QuerySchema;
import org.imeta.orm.schema.SimpleCondition;

import java.math.BigDecimal;
import java.util.*;


/**
 * @author lixilin
 * @Description: 联产品权重保存, 删除, 停用启用规则
 * @date 2020/6/19
 */
public class SaveUnionRealWeightBillRule extends AbstractCommonRule {
    @Override
    public RuleExecuteResult execute(BillContext billContext, Map<String, Object> paramMap) throws Exception {
        RuleExecuteResult ruleResult = new RuleExecuteResult();
        // 获取前台传递过来的数据
        List<BizObject> bills = getBills(billContext, paramMap);
        // 主表数据
        UnionRealWeight tmp = (UnionRealWeight) bills.get(0);
        LoginUser user = AppContext.getCurrentUser();

        QueryConditionGroup queryConditionGroup = QueryConditionGroup.and(
                QueryCondition.name("productType").eq(ProductType.MainProduct.getValue())
                ,QueryCondition.name("iaMaterialId").eq(tmp.getMainPcmProduct())
                ,QueryCondition.name("stopstatus").eq(Boolean.FALSE)
        );
        QuerySchema schema = QuerySchema.create().addSelect("id").addCondition(queryConditionGroup);
        List<Map<String, Object>> data = MetaDaoHelper.query(RealCo.ENTITY_NAME, schema);
        if (CollectionUtils.isEmpty(data)) {
            throw new BusinessException(ResponseMessage.MUST_SELECT_MAIN_PRODUCT);
        }

        // 行数据
        List<BizObject> billDataList = bills.get(0).get("pcm_UnionRealWeight_card_sub1");
        if (CollectionUtils.isNotEmpty(billDataList)) {
            List<UnionRealWeight> insertList = new ArrayList<>();
            List<UnionRealWeight> updateList = new ArrayList<>();
            StringBuilder auditValueBuilder = new StringBuilder(200);
            billDataList.forEach(bizObj -> {
                UnionRealWeight unionRealWeight = new UnionRealWeight();
                BigDecimal convertRatio = bizObj.get("convertRatio") == null ? BigDecimal.ONE : new BigDecimal(bizObj.get("convertRatio").toString());
                unionRealWeight.setConvertRatio(convertRatio);
                BigDecimal costweight = bizObj.get("costweight") == null ? BigDecimal.ZERO : new BigDecimal(bizObj.get("costweight").toString());
                unionRealWeight.setCostweight(costweight);
                unionRealWeight.setConvert(getConvertVal(bizObj.get("convert")));
                if (bizObj.get("id") != null) {
                    unionRealWeight.setId(NumberUtils.L(bizObj.get("id")));
                    unionRealWeight = (UnionRealWeight)PcmHelper.setOtherAttr(user, unionRealWeight, 2);
                    unionRealWeight.setEntityStatus(EntityStatus.Update);
                    if (Objects.nonNull(bizObj.get("_status")) && "delete".equalsIgnoreCase(bizObj.get("_status").toString())) {
                        unionRealWeight.setEntityStatus(EntityStatus.Delete);
                    }else {
                        //审计值 =>  工厂+主成本对象+关联成本对象+关联对象类型+是否折算+折算系数+成本权重
                        unionRealWeight.setAuditValue(PcmVoucherUtils.getUnionRealWeightAuditValue(auditValueBuilder,unionRealWeight));
                    }
                    updateList.add(unionRealWeight);
                }else {
                    unionRealWeight.setAccPurposes(tmp.getAccPurposes());
                    unionRealWeight.setControlScope(tmp.getControlScope());
                    unionRealWeight.setAccentity(tmp.getAccentity());
                    unionRealWeight.setBusiaccbook(tmp.getBusiaccbook());
                    unionRealWeight.setMainPcmProduct(tmp.getMainPcmProduct());
                    unionRealWeight.setSubPcmProduct(NumberUtils.L(bizObj.get("subPcmProduct")));
                    unionRealWeight.setFactory(tmp.getFactory());

                    // 21-6-7生产部门给空字符串
                    String productionDept = tmp.getProductionDept();
                    if (Objects.isNull(productionDept) || "null".equalsIgnoreCase(productionDept)) {
                        unionRealWeight.setProductionDept("");
                    }

                    ProductType productType = ProductType.find(NumberUtils.s(bizObj.get("productType")));
                    unionRealWeight.setProductType(productType);
                    unionRealWeight = (UnionRealWeight)PcmHelper.setOtherAttr(user, unionRealWeight, 1);
                    unionRealWeight.setEntityStatus(EntityStatus.Insert);
                    //审计值 =>  工厂+主成本对象+关联成本对象+关联对象类型+是否折算+折算系数+成本权重
                    unionRealWeight.setAuditValue(PcmVoucherUtils.getUnionRealWeightAuditValue(auditValueBuilder,unionRealWeight));
                    insertList.add(unionRealWeight);
                }
            });
            if (CollectionUtils.isNotEmpty(insertList)) {
                MetaDaoHelper.insert(billContext.getFullname(), insertList);
            }
            if (CollectionUtils.isNotEmpty(updateList)) {
                MetaDaoHelper.update(billContext.getFullname(), updateList);
            }
            // 保存当前操作的会计主体，用于下次带出
            BillMasterOrgService.insertLastOrg(billContext.getBillnum());
        }
        return ruleResult;
    }

    private boolean getConvertVal(Object convert){
        String conVal = convert+"";
        if ("false".equalsIgnoreCase(conVal) || "0".equalsIgnoreCase(conVal)) {
            return false;
        }
        return true;
    }

    private List<SimpleCondition> getSimpleConditionsList(UnionRealWeight tmp, LoginUser user) {
        List<SimpleCondition> conditions = new ArrayList<>();
        conditions.add(new SimpleCondition("tenant", ConditionOperator.eq, user.getTenant()));
        if (tmp.getAccPurposes() != null) {
            conditions.add(new SimpleCondition("accPurposes", ConditionOperator.eq, tmp.getAccPurposes()));
        }
        if (tmp.getControlScope() != null) {
            conditions.add(new SimpleCondition("controlScope", ConditionOperator.eq, tmp.getControlScope()));
        }
        if (tmp.getAccentity() != null) {
            conditions.add(new SimpleCondition("accentity", ConditionOperator.eq, tmp.getAccentity()));
        }
        if (tmp.getBusiaccbook() != null) {
            conditions.add(new SimpleCondition("busiaccbook", ConditionOperator.eq, tmp.getBusiaccbook()));
        }
        if (tmp.getFactory() != null) {
            conditions.add(new SimpleCondition("factory", ConditionOperator.eq, tmp.getFactory()));
        }
        if (tmp.getMainPcmProduct() != null) {
            conditions.add(new SimpleCondition("mainPcmProduct", ConditionOperator.eq, tmp.getMainPcmProduct()));
        }
        return conditions;
    }
}
